import { addUser } from '@/services/userService';
import { ProColumns, ProTable } from '@ant-design/pro-components';
import { message, Modal } from 'antd';
import React, { PropsWithChildren } from 'react';

interface CreateModalProps {
  modalVisible: boolean;
  columns: ProColumns<UserType.User>[];
  onSubmit: () => void;
  onCancel: () => void;
}

/**
 * 添加节点
 * @param fields
 */
const handleAdd = async (fields: UserType.User) => {
  const hide = message.loading('正在添加');
  try {
    await addUser({ ...fields } as UserType.UserAddRequest);
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 创建数据模态框
 * @param props
 * @constructor
 */
const CreateModal: React.FC<PropsWithChildren<CreateModalProps>> = (props) => {
  const { modalVisible, columns, onSubmit, onCancel } = props;

  // 创建用户时需要的额外字段
  const createColumns: ProColumns<UserType.User>[] = [
    ...columns
      .filter((column) => !['option', 'createTime', 'updateTime'].includes(column.dataIndex as string))
      .map((column) => {
        // 账号字段添加必填标记和验证规则
        if (column.dataIndex === 'userAccount') {
          return {
            ...column,
            formItemProps: {
              ...column.formItemProps,
              rules: [
                {
                  required: true,
                  message: '请输入账号',
                },
              ],
            },
          };
        }
        // 用户昵称字段确保不默认填充
        if (column.dataIndex === 'userName') {
          return {
            ...column,
            initialValue: undefined,
          };
        }
        return column;
      }),
    {
      title: '密码',
      dataIndex: 'userPassword',
      valueType: 'password',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '请输入密码',
          },
          {
            min: 8,
            type: 'string',
            message: '密码长度不能小于 8',
          },
        ],
      },
    },
  ];

  return (
    <Modal
      destroyOnClose
      title="新建用户"
      open={modalVisible}
      onCancel={() => onCancel()}
      footer={null}
    >
      <ProTable<UserType.User, UserType.User>
        onSubmit={async (value) => {
          const success = await handleAdd(value);
          if (success) {
            onSubmit?.();
            onCancel();
          }
        }}
        rowKey="id"
        type="form"
        columns={createColumns}
        form={{
          initialValues: {
            userName: '',
            userPassword: '',
            userAccount: ''
          }
        }}
      />
    </Modal>
  );
};

export default CreateModal;
